<template>
  <div
    class="draft-editor bg-white flex w-full"
    :data-has-draft="!!(draftContent || hasAttachments)"
  >
    <!-- 提示占位用 -->
    <div
      v-if="inputIndicator"
      class="
        is-inactive flex w-full px-5 py-3 border-t border-solid border-gray-200
      "
    >
      <div
        class="
          px-3 py-2 w-full rounded teld-bg-color-gray teld-color-lightgray
          truncate
        "
        style="height:36px"
        @click="showInputPopup">{{
        trimmedContent || placeholder
      }}
      </div>
    </div>

    <!-- 弹出层输入框 -->
    <t-dialog
      v-model:show="isFocused"
      position="bottom"
      class=""
    >
      <div
        class="popup-for-draft-editor bg-white"
        :style="{
          borderRadius: '16px 16px 0 0',
          height: isFullscreen ? 'calc(100vh - 180px)' : '280px',
          overflow: 'hidden',
          boxShadow: 'rgba(0, 0, 0, 0.1) 0px 0px 8px 2px, rgba(0, 0, 0, 0.1) 0px 0 6px -2px'
        }"
      >
        <!-- 主体 -->
        <div
          ref="inputWrapperRef"
          class="
            right-main flex flex-col rounded relative
            box-border px-5 py-4 overflow-hidden h-full
          "
          :class="[isFocused ? '' : 'h-0']"
          @click="onClickInputWrapper"
        >
          <div class="flex flex-1 overflow-hidden relative pb-4">
            <!-- 输入框 -->
            <div
              ref="draftEditorInputRef"
              :contenteditable="visible"
              class="
                draft-editor--input
                h-full w-full
                box-border
                overflow-x-hidden
                overflow-y-auto
              "
              style="white-space:pre-wrap;word-break:break-all;"
              @paste="onPaste"
            ></div>
            <!-- 切换全屏大小的图标按钮 -->
            <!-- <div class="icons-toggle">
              <ToFullscreen v-show="!isFullscreen" @click.capture.stop.prevent="toggleFullscreen" />
              <ToWindowed v-show="isFullscreen" @click.capture.stop.prevent="toggleFullscreen" />
            </div> -->
            <!-- 占位提示 -->
            <div
              v-show="!this.draftContent"
              class="draft-placeholder pointer-events-none absolute teld-color-lightgray"
            >{{ placeholder }}</div>

            <!-- 已输入长度/限制长度 -->
            <div
              class="
                draft-content-counting
                absolute right-0 bottom-0
              "
              :class="[ isInputOverflow ? 'teld-color-red' : 'teld-color-lightgray']"
              style=""
            >
              {{ draftWordLength }}/{{ inputMaxLength }}
            </div>
          </div>

          <!-- 附件 -->
          <div
            v-show="fileList.length"
            class="
              file-list-preview py-3 pr-2 w-full
              border-b border-solid border-gray-100
              flex no-wrap overflow-x-auto
            "
          >
            <div
              v-for="(fileItem, fileIndex) in fileList"
              :key="fileItem.file.name + fileItem.file.lastModified"
              class="relative h-20 mr-2 "
            >
              <!-- <tm-loading
                v-if="fileItem && fileItem.status !== 'done'"
                type="spinner"
                class="
                  absolute w-full h-full flex justify-center items-center
                  opacity-20 text-white bg-black
                "
              ></tm-loading> -->
              <t-inner-loading :showing="fileItem && fileItem.status !== 'done'">
                <t-spinner size="28px" color="primary" />
              </t-inner-loading>

              <img
                v-if="
                  fileItem.file.type == 'image/jpeg' ||
                  fileItem.file.type == 'image/png' ||
                  fileItem.file.type == 'image/jpg' ||
                  fileItem.file.type == 'image/gif'
                "
                :src="fileItem.content"
                alt="Image"
                class="attachment-image w-28 h-20 border border-solid border-gray-100 rounded"
                @click="onClickImage"
              />
              <div
                v-else
                style="
                  background-color: #f5f5f5;
                "
                class="p-2 flex flex-col justify-between rounded w-28 h-20 box-border"
              >
                <!-- 文件类型图标 -->
                <FileTypeIcon
                  :file-name="fileItem.file && fileItem.file.name"
                  class="w-6 h-6 self-center"
                />
                <div class="van-multi-ellipsis--l2 text-xs">
                  {{ fileItem.file.name }}
                </div>
              </div>
              <!-- 删除附件 -->
              <div
                class="file-remove-icon-container absolute -top-1 -right-1"
                @click="handleRemoveFile(fileIndex)"
              >
                <Clear class="w-5 h-5 bg-white rounded-full" style="color:#8a8a8a" />
              </div>
            </div>
          </div>

          <!-- 底部按钮行 -->
          <div
            class="
              operation-wrap flex justify-between items-center pt-2
              border-t border-solid border-gray-100
            "
          >
            <div class="left teld-theme-color pl-1">
              <At
                class="teld-theme-color cursor-pointer mr-3"
                @click.native.capture.stop="onClickAt"
              />
              <Attachment
                class="teld-theme-color cursor-pointer"
                @click.native.capture.stop="toAddAttachment"
              />
                <!-- 附件图标 -->
              <!-- <tm-uploader
                ref="uploaderRef"
                :before-read="beforeRead"
                :after-read="afterRead"
                accept="*/*"
                multiple
                class="mr-5"
              >
                <div
                  class="teld-theme-color cursor-pointer"
                >
                  <Attachment />
                </div>
              </tm-uploader> -->
              <!-- 上传文件用的 input -->
              <input
                ref="fileInputRef"
                type="file"
                multiple
                style="opacity: 0; width: 0; height: 0"
                @change="onInputFileChange"
              />
            </div>
            <div class="right">
              <t-button
                color="primary"
                @click.capture.top="onClickPublishComment"
              >{{ buttonText }}</t-button>
            </div>
          </div>

          <div v-if="isInputLoading" class="absolute inset-0 rounded">
            <t-inner-loading :showing="isInputLoading">
              <t-spinner size="20px" color="primary" />
            </t-inner-loading>
          </div>
        </div>

        <!-- 大图查看 -->
        <t-image-preview
          ref="imagePreviewRef"
          v-model="currentImgSrc"
          :src-list="previewSrcList"
        ></t-image-preview>
      </div>
    </t-dialog>

    <!-- 选人弹窗 -->
    <PersonnelSelectorPopup
      v-model:visible="personnelSelectorPopupVisible"
      @selected="onSelectPersonnel"
    >
    </PersonnelSelectorPopup>
  </div>
</template>

<script>
// Components
import ToFullscreen from "../../components/svg-icons/to-fullscreen.vue";
import ToWindowed from "../../components/svg-icons/to-windowed.vue";
import At from "../../components/svg-icons/at.vue";
import Attachment from "../../components/svg-icons/attachment.vue";
import Clear from "../../components/svg-icons/clear.vue";
import UserAvatar from '../../components/user-avatar/index.vue';
import FileTypeIcon from '../../components/file-type-icon/index.vue';
import PersonnelSelectorPopup from '../personnel-selector-popup/index.vue';

// Utils
import { reactive } from 'vue';
import {
  readAsBase64,
  isSupportedImageType,
  formatBytes,
  replaceAtUser,
  getMentionedUserIdList,
  getNotEditableContent,
} from '../../hooks';
import { apiUploadFile } from '../../hooks/api';
import {
  SUPPORTED_FILE_TYPES,
  ATTACHMENT_MAX_COUNT,
  SUBMIT_CONTENT_LIMIT,
} from '../../utils';

/**
 * [移动端用]草稿输入框组件
 */
export default {
  name: "TmDraftEditor",
  // inject: ['qLangComment', "loginUserInfo", 'getAttachmentMaxSize'],
  inject: [
    'qLangComment',
    'loginUserInfo',
    'getAttachmentMaxSize',
    // 'getContainerForPersonnelSelectorPopup', // PC端弹出快捷选人用的
    'updateRecentlyMentionedUsers', // 更新最近提及的用户
    'emitEvent',
    //
    'inputMaxLength',
    'sendButtonText',
  ],
  props: {
    isComment: {
      type: Boolean,
      default: false,
    },
    /**透传visible用于点开时给editor赋焦点*/
    visible: {
      type: Boolean,
      default: false,
    },
    /**是否可独立窗口打开*/
    canBeIndependent: {
      type: Boolean,
      default: false,
    },
    showAvatar: {
      type: Boolean,
      default: false,
    },
    autoClearOnHidding: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '',
    },
    inputIndicator: {
      type: Boolean,
      default: false,
    }
  },
  components: {
    ToFullscreen,
    ToWindowed,
    At,
    Attachment,
    Clear,
    UserAvatar,
    FileTypeIcon,
    PersonnelSelectorPopup,
  },
  watch: {
    visible(val) {
      if (val) {
        !this.inputIndicator && this.showInputPopup();
      } else {
        this.autoClearOnHidding && this.reset();
      }
    },
    isFocused(val) {
      if (val) {
        this.$nextTick(()=>{
          this.$refs.draftEditorInputRef.innerHTML = this.draftContent;
          this.bindEvents();
        })
      } else {
        this.isFullscreen = false;
        if (!this.inputIndicator) {
          this.$emit('update:visible', false);
        }
        this.unbindEvents();
      }
    },
  },
  computed: {
    hasAttachments() {
      return !!this.fileList.length && this.fileList.some(n=>n.status ==='done');
    },
    isInputOverflow() {
      return this.draftWordLength > this.inputMaxLength;
    },
    isFileCountOverflow() {
      return this.fileList.length >= ATTACHMENT_MAX_COUNT;
    },
    attachmentTips() {
      // return `附件限制${ATTACHMENT_MAX_COUNT}个以内，支持如下文件类型：${SUPPORTED_FILE_TYPES}`;
      return this.qLangComment.funcAttachmentLimit([
        ATTACHMENT_MAX_COUNT,
        SUPPORTED_FILE_TYPES,
      ]);
    },
    buttonText() {
      const btnText = this.sendButtonText;
      return btnText && btnText.trim()
        ? btnText.trim()
        : this.isComment
          ? this.qLangComment.comment
          : this.qLangComment.reply;
    },
  },
  data() {
    return {
      fileList: [],
      // fileList: [
      //   {
      //     file:{
      //       name:'test-image.png',
      //       uid: '1708939944188',
      //       size:'1323423',
      //       type: 'image/png',
      //     },
      //     result: {
      //       "CommentID": null,
      //       "AttachmentType": 0,
      //       "AttachmentUrl": "http://resource.teld3.xyz/teldimage/160/a8e5edf5f8fa4ac2800647b17fe74cbe.png",
      //       "UploadTime": "2024-02-26T18:07:16.198832+08:00",
      //       "ID": "506d7f62-b062-478c-b9bf-251d7f6f39ec",
      //       "Creator": null,
      //       "CreateTime": "0001-01-01T00:00:00",
      //       "LastModifier": null,
      //       "LastModifyTime": "0001-01-01T00:00:00"
      //     },
      //     content: 'http://resource.teld3.xyz/teldimage/160/a8e5edf5f8fa4ac2800647b17fe74cbe.png',
      //     message: '',
      //     status: 'done',
      //    }
      // ],
      draftContent: "", // 要提交的富文本内容
      draftWordLength: 0, // 纯文本字数，包含空格
      trimmedContent: "", // 草稿缩略显示用文字内容
      isInputLoading: false,
      // isInputEmpty: false,
      isFocused: false,
      isFullscreen: false,
      // 用于保持光标位置
      savedRange: null,
      //
      previewSrcList: [],
      currentImgSrc: '',
      //
      personnelSelectorPopupVisible: false,
    };
  },
  mounted() {
    this.bindEvents();
    setTimeout(() => {
      // 通过setTimeout确保上面绑定的focus事件会被执行
      // this.initFocus();
    });
  },
  beforeDestroy() {
    this.unbindEvents();
  },
  methods: {
    bindEvents() {
      const inputBox = this.$refs.draftEditorInputRef;
      if (inputBox) {
        inputBox.addEventListener("input", this.onInput);
      }
    },
    unbindEvents() {
      const inputBox = this.$refs.draftEditorInputRef;
      if (inputBox) {
        inputBox.addEventListener("input", this.onInput);
      }
    },
    initFocus() {
      const inputBox = this.$refs.draftEditorInputRef;
      inputBox.scrollTop = inputBox.scrollHeight;
      const range = new Range();
      range.selectNodeContents(inputBox);
      range.collapse(false);
      const selection = getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
      setTimeout(() => {
        inputBox.focus();
      }, 300);
    },
    onInput(e) {
      console.log("onInput", e);

      // Backspace删除时，阻止浏览器在删光内容后自动添加`<br>`的行为
      if (e.inputType === 'deleteContentBackward') {
        const innerHTML = this.$refs.draftEditorInputRef.innerHTML;
        if (innerHTML === '' || innerHTML.toLowerCase() == '<br>') {
          e.preventDefault();
          this.$refs.draftEditorInputRef.innerHTML = '';
        }
      }
      // 直接输入`@`和[Backspace,ArrowLeft,ArrowRight]等造成光标落到`@`时
      const lastChar = e.data || e.target.innerText.slice(-1);
      if (lastChar === '@') {
        this.handleAtInput();
      }

      this.draftContent = e.target.innerHTML;
      this.trimmedContent = e.target.textContent.trim();
      this.draftWordLength = e.target.innerText.length; // 含空格
    },
    onPaste(e) {
      e.preventDefault();
      const clipboardData = (e.originalEvent || e).clipboardData;
      if (!clipboardData) {
        return;
      }
      const pastedText = clipboardData.getData('text/plain');
      if (pastedText) {
        console.log('clipboardData text/plain', pastedText)
        document.execCommand('insertText', false, pastedText);
      }
    },
    onClickAt() {
      const inputBox = this.$refs.draftEditorInputRef;
      inputBox.focus();
      const txtAt = new Text('@');
      inputBox.appendChild(txtAt);
      inputBox.dispatchEvent(new Event('input'));

      const selection = getSelection();
      selection.removeAllRanges();
      const range = new Range();
      range.selectNode(txtAt);
      selection.addRange(range);
      range.collapse(false);
      // 点按钮时手动插入一个`@`所以固定的 offset=1
      selection.collapse(txtAt, 1);
      this.handleAtInput();
    },
    handleAtInput() {
      // this.queryUserName = getAtUser();
        // 动态确定参照系父元素
        // this.offsetParentElement =
        //   this.offsetParent ||
      //   this.getContainerForPersonnelSelectorPopup(this.isComment);

      this.savedRange = window.getSelection().getRangeAt(0);
      this.personnelSelectorPopupVisible = true;
    },
    /**
     * 点击发布评论/回复按钮的处理
     *
     * @description
     *  - 关于提交内容非空检查
     *    - 无附件时，不允许空提交，仅空格、仅回车、仅空格加回车都不行
     *    - 有附件时，允许空提交，仅空格、仅回车、仅空格加回车时，内容置换为空文字
     */
    onClickPublishComment() {
      if (this.isInputLoading) return;

      // 移动端没有粘贴图片的功能，所以下面检查富文本内容不考虑图片
      const inputBox = this.$refs.draftEditorInputRef;

      // 没有有效内容，且没有附件时
      if (!this.trimmedContent && !this.hasAttachments) {
        // this.$TM.Toast('请检查输入内容');
        this.$q.notify({
          // message: '请检查输入内容',
          message: this.qLangComment.msgCheckInput,
          icon: 'warning_amber',
          type: 'warning',
          textColor: 'white',
          position: 'top',
          timeout: 2000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'warning', // 这是为了做精准选择器调样式用的
          },
        });
        this.initFocus();
        return;
      }

      if (this.isInputOverflow) {
        // this.$TM.Toast('内容超出文字数上限');
        this.$q.notify({
          message: this.qLangComment.inputTooLong,
          icon: 'warning_amber',
          type: 'warning',
          textColor: 'white',
          position: 'top',
          timeout: 2000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'warning', // 这是为了做精准选择器调样式用的
          },
        });
        this.initFocus();
        return;
      }

      if (this.draftContent.length > SUBMIT_CONTENT_LIMIT) {
        // this.$TM.Toast(`内容超出可提交文字数上限(${this.draftContent.length}/${SUBMIT_CONTENT_LIMIT})`);
        this.$q.notify({
          message: `${qLangComment.errSubmitContentTooLong}(${this.draftContent.length}/${SUBMIT_CONTENT_LIMIT})`,
          icon: 'warning_amber',
          type: 'warning',
          textColor: 'white',
          position: 'top',
          timeout: 2000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'warning', // 这是为了做精准选择器调样式用的
          },
        });
        this.initFocus();
        return;
      }

      this.isInputLoading = true;
      const userIdList = getMentionedUserIdList(inputBox);
      const content = this.trimmedContent ? encodeURIComponent(getNotEditableContent(inputBox)) : '';
      this.$emit('comment', {
        content,
        fileList: this.fileList,
        fileList: this.fileList.filter(n => n.result && n.status === 'done'),
        userIdList,
        onSucceed: (args = {}) => {
          this.$q.notify(this.qLangComment.msgSendSuccess);
          this.reset(args);
          this.emitEvent('comment', {
            content,
            mentionedUsers: userIdList,
          });
        },
        onFail: (args = {}) => {
          this.$q.notify(this.qLangComment.msgSendFail);
          this.isInputLoading = false;
        }
      });
    },
    reset({focus} = {}) {
      this.isInputLoading = false;
      // 清空内容
      const inputBox = this.$refs.draftEditorInputRef;
      if (inputBox) {
        inputBox.innerHTML = '';
      }
      this.draftContent = '';
      this.trimmedContent = '';
      this.draftWordLength = 0;
      this.fileList = [];
      // TODO PC端的tp-upload自定义上传需要手动清空文件，tm-uploader待确认
      // this.$refs.uploaderRef.clearFiles();

      // 主列表中添加评论后继续设回焦点
      if (focus) {
        setTimeout(() => {
          this.$refs.draftEditorInputRef.focus();
        }, 500)
      } else {
        this.isFocused = false;
      }
    },
    /**
     * -------------------------
     */
    showInputPopup() {
      this.isFocused = true;
      setTimeout(() => {
        this.initFocus();
      });
    },
    toggleFullscreen(e) {
      this.isFullscreen = !this.isFullscreen;
      this.initFocus();
    },
    onClickInputWrapper(e) {
      // const inputBox = this.$refs.draftEditorInputRef;
      // if (!inputBox.contains(e.target)) {
      //   this.initFocus();
      // }
    },
    onSelectPersonnel(items) {
      const inputBox = this.$refs.draftEditorInputRef;
      inputBox.focus();
      const selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(this.savedRange);
      replaceAtUser(items);
      this.savedRange = null;

      inputBox.dispatchEvent(new Event('input'));
      this.updateRecentlyMentionedUsers(items);
    },
    /**
     * -------------------------
     * 附件/文件上传相关 start
     */
    toAddAttachment() {
      this.$refs.fileInputRef.click();
    },
    onInputFileChange(e) {
      const files = Array.from(e.target.files);
      for(let i = 0; i < files.length; i++) {
        this.onFileChange(files[i]);
      }
      e.target.value = '';
    },
    /** 选取文件后的处理，检查通过后直接上传 */
    async onFileChange(file) {
      console.log('file', file);

      // check file size
      const sizeBytes = this.getAttachmentMaxSize();
      if (file.size > sizeBytes) {
        const sizeFormat = formatBytes(sizeBytes);
        // this.$TP.$message.warning(`请上传 ${sizeFormat} 以内的附件`);
        this.$q.notify({
          // message: `请上传 ${sizeFormat} 以内的附件`,
          message: this.qLangComment.funcFileSizeLimit(sizeFormat),
          // icon: '',
          type: 'warning',
          textColor: 'white',
          position: 'top',
          timeout: 1000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'warning', // 这是为了做精准选择器调样式用的
          },
        });
        return false;
      }

      // check file type
      const fileExt = file.name.split('.').pop();
      const checkFileType = SUPPORTED_FILE_TYPES.split(',').includes(fileExt);
      if (!checkFileType) {
        // this.$TP.$message.info(`不支持的文件类型(${file.name})`);
        this.$q.notify({
          // message: `不支持的文件类型(${file.name})`,
          message: this.qLangComment.funcFileTypeNotSupport(file.name),
          // icon: '',
          type: 'info',
          textColor: 'white',
          position: 'top',
          timeout: 1000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'info', // 这是为了做精准选择器调样式用的
          },
        });
        return;
      }

      this.uploadFile(file);
    },
    /**
     * 上传文件的处理
     * 通过 file.status 控制 loading 状态
     */
    async uploadFile(file) {
      // file.status = 'ready'; // 文件状态，原el-upload包装属性
      const [strWithType, base64Str] = await readAsBase64(file);
      if (!base64Str) {
        // this.$TP.$message.warning(`文件内容为空(${file.name})`);
        this.$q.notify({
          // message: `文件内容为空(${file.name})`,
          message: this.qLangComment.funcEmptyFile(file.name),
          // icon: '',
          type: 'warning',
          textColor: 'white',
          position: 'top',
          timeout: 1000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'warning', // 这是为了做精准选择器调样式用的
          },
        });
        return;
      }

      // check file duplicated
      if (this.fileList.some(n => n.content === strWithType)) {
        // this.$TP.$message.info(`文件重复上传(${file.name})`);
        this.$q.notify({
          // message: `文件重复上传(${file.name})`,
          message: this.qLangComment.funcFileDuplicated(file.name),
          // icon: '',
          type: 'info',
          textColor: 'white',
          position: 'top',
          timeout: 1000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'info', // 这是为了做精准选择器调样式用的
          },
        });
        return;
      }

      // let retFlag = false;
      const onFail = () => {
        // file.status = 'failed';
        // this.$TP.$message.error(`上传失败(${file.name})`);
        this.$q.notify({
          // message: `上传失败(${file.name})`,
          message: this.qLangComment.funcUploadFailed(file.name),
          // icon: '',
          type: 'negative',
          textColor: 'white',
          position: 'top',
          timeout: 1000,
          attrs: {
            // 为通知的 DOM 本身设置属性:
            'comment-notification': 'negative', // 这是为了做精准选择器调样式用的
          },
        });
        // 上传失败后上传组件中去掉该文件
        this.fileList = this.fileList.filter(n => n.uid !== newFile.uid);
      };
      const newFile = reactive({
        file,
        result: {},
        uid: Date.now(),
        status: 'ready',
        content: strWithType,
      });
      this.fileList.push(newFile);

      try {
        // const res = await this.$utils.sgApi.getDataAsync({
        //   url: this.$utils.common.getServiceUrl('CMTS-UploadAttachment'),
        //   data: {
        //     param: JSON.stringify({
        //       FileName: file.name,
        //       FileContent: strWithType,
        //     }),
        //   },
        // });
        const res = await apiUploadFile({
          fileName: file.name,
          fileContent: strWithType,
        });
        console.log('mobile upload file', res);

        if (!res || res.state !== '1') {
          onFail();
          return;
        }

        // retFlag = true;
        // file.status = 'done';
        newFile.status = 'done';
        newFile.result = res.data;
      } catch (error) {
        onFail();
      }
    },
    // ----- deprecated start -----
    /**
     * tm-uploader读取文件内容前的处理，用于检查是否符合上传要求
     * 参数 file<File> 与 afterRead 里的不同
     */
    beforeRead(file, detail) {
      console.log('beforeRead', file, detail);
      // check file type
      const fileExt = file.name.split('.').pop();
      const checkFileType = SUPPORTED_FILE_TYPES.split(',').includes(fileExt);
      if (!checkFileType) {
        this.$TM.Toast(`不支持的文件类型(${file.name})`);
        return false;
      }

      // check file size
      const sizeBytes = this.getAttachmentMaxSize();
      if (file.size > sizeBytes) {
        const sizeFormat = formatBytes(sizeBytes);
        this.$TM.Toast(`请上传 ${sizeFormat} 以内的附件`);
        return false;
      }

      return true;
    },
    /**
     * tm-uploader组件读取文件内容后的处理
     *
     * file数据结构
     *  {
     *    content,
     *    file: <File> {
     *      lastModified,
     *      lastModifiedDate,
     *      name,
     *      size,
     *      type,
     *      webkitRelativePath,
     *    },
     *    message,
     *    status,
     *    result: Object<接口返回的结果>
     *  }
     */
    async afterRead(file, detail) {
      console.log('afterRead', file, detail);
      const onFail = (info) => {
        console.log(info);
        file.status = 'failed';
        this.$TM.Toast(`上传失败(${file.file.name})`);
        this.fileList.pop();
      }

      const base64String = file.content.split(',')[0];
      if (!base64String) {
        $TM.Toast(`文件内容为空(${file.file.name})`);
        return;
      }

      file.status = 'uploading';
      this.fileList.push(file);

      try {
        // const { data } = await this.$utils.sgApi.getDataAsync({
        //   url: this.$utils.common.getServiceUrl('CMTS-UploadAttachment'),
        //   data: { param: JSON.stringify({
        //     FileName: file.file.name,
        //     FileContent: file.content,
        //   }) },
        // });
        const res = await apiUploadFile({
          fileName: file.name,
          fileContent: strWithType,
        });
        console.log('UploadAttachment', res);
        if (!res || res.state !== '1' ) {
          setTimeout(() => {
            onFail();
          }, 1500);
          return;
        }

        file.result = res.data;

        // file.result = {
        //   "CommentID": null,
        //   "AttachmentType": 2,
        //   "AttachmentUrl": "http://resource.teld3.xyz/teldimage/160/b3112f4f607f49efa4c2c6a253b00cd3.png",
        //   "UploadTime": "2024-02-27T14:56:15.0019732+08:00",
        //   "FileName": "附件上传的方式对比.docx",
        //   "ID": "16ead4d7-62dd-44fb-acfc-b8c8675f7010",
        //   "Creator": null,
        //   "CreateTime": "0001-01-01T00:00:00",
        //   "LastModifier": null,
        //   "LastModifyTime": "0001-01-01T00:00:00"
        // },
        setTimeout(() => {
          file.status = 'done';
        }, 500);
      } catch (error) {
        setTimeout(() => {
          onFail(error);
        }, 500);
      }
    },
    // ----- deprecated end -----
    /**删掉添加的附件*/
    handleRemoveFile(index) {
      this.fileList.splice(index, 1);
    },
    /**点击附件图片进行大图查看*/
    onClickImage(e) {
      // this.$TM.ImagePreview({images:[e.target.currentSrc]});
      const previwer = this.$refs.imagePreviewRef;
      if (previwer) {
        previwer.open(e.target.currentSrc);
      }
    },
    /**
     * 附件/文件上传相关 end
     * -------------------------
     */

  },
};
</script>

<style lang="scss" scoped></style>
